﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EmotionRecognitionEntities;
using EmotionRecognitionMessages;
using System.Threading.Tasks;
//
namespace EmotionRecognitionGui
{
    public partial class DataBaseImages : ImageAnalysis
    {

        GuiManager guiManager;
        bool isRefinementUsed = false;
        static int counter = 0;
        int i = 0;
        int firstpictureID = 0;

        Picture currentDisplayedPicture;
        protected Dictionary<Chunk, Case> solutions;
        Dictionary<int, Picture> DatabasepictureDictionary;

        Messages retrievalmsg = new Messages();

        public DataBaseImages()
        {
            try
            {

                guiManager = GuiManager.Instance;
                InitializeComponent();
                base.DisposeObjectsInherent();
                labelRefinementAlert.Visible = false;
                // DisposeObjectsInherent();
            }
            catch (Exception e)
            {
                MessageBox.Show("Error: " + e.ToString());
            }
        }

        new public void ReEnter()
        {
            ShowFirstImage();
            labelRefinementAlert.Visible = false;
        }
        public void RefreshPictureSolution()
        {
            showCurrentAusinListbox();
            RunRetrieval(currentDisplayedPicture.AUList);
        }

        public void ShowFirstImage()
        {
            ReplyMsg reply = retrievalmsg.LoadPicutersFromDB(1);
            if (reply.MessageState)
                DatabasepictureDictionary = (Dictionary<int, Picture>)reply.ParamArray[0];
            if (DatabasepictureDictionary.Count != 0)
            {
                pictureBoxImage.Image = DatabasepictureDictionary.Values.First().PictureImage;
                currentDisplayedPicture = DatabasepictureDictionary.Values.First();
                pictureIDmaskedBox.Text = currentDisplayedPicture.PictureID.ToString();
                firstpictureID = DatabasepictureDictionary.Values.First().PictureID;
                pictureBoxImage.SizeMode = PictureBoxSizeMode.Zoom;
                showCurrentAusinListbox();
                firstpictureID = currentDisplayedPicture.PictureID;
                i = firstpictureID;
                if (currentDisplayedPicture.AUList.Count != 0)
                {
                    RunRetrieval(currentDisplayedPicture.AUList);
                }
                counter = 0;
            }
        }

        protected void buttonFeedback_Click(object sender, EventArgs e)
        {
            guiManager.userFeedBackGui.ReEnter(solutions, currentDisplayedPicture,isRefinementUsed);
            guiManager.SwitchForms(this, guiManager.userFeedBackGui);
        }
        new protected void buttonBack_Click(object sender, EventArgs e)
        {
            guiManager.SwitchForms(this, guiManager.mainMenuReviewerGui);
        }

        
        protected void nextImageButton_Click(object sender, EventArgs e)
        {
            RunRetrieval(ShowNextImage());
        }

        protected void AddAutoPicture(int au,Picture picture)
        {
            if (picture.AUList.Count==0)
                  picture.AUList = new List<int>();
            picture.AUList.Add(au);
            currentAUlistbox.Items.Add(au);
        }




        protected  void RunRetrieval(List<int> aulist)
        {
            //copy of is auList is needed- because inside retreival auList has been deleted
            // so copy is sent to retrieval
            List<int> copyofAuList= new List<int>();

            foreach (int au in aulist)
            {
                copyofAuList.Add(au);
            }
            ReplyMsg replymsg = retrievalmsg.ExecuteRetrievalAlgorithm(copyofAuList);
            if (replymsg.MessageState == true)
            {
                solutions = (Dictionary<Chunk, Case>)replymsg.ParamArray[0];
                ShowSolutions();
                if (solutions.Count == 0) //if the picture contains new aus each of which not in db then create new case and derive solutions for adaptation
                {
                    Dictionary<Chunk, Case> newCaseByInput = new Dictionary<Chunk, Case>();
                    Case newCase = new Case();
                    newCase.ExistsInDb = false;
                    newCase.AuList = copyofAuList;
                    Chunk falseChunk = new Chunk(-1,"");
                    newCaseByInput.Add(falseChunk, newCase);
                    solutions = newCaseByInput;
                }
            }
        }

        protected List<int> ShowNextImage()
        {
            
            
            if (DatabasepictureDictionary.Count == 1)
            {
                firstpictureID = DatabasepictureDictionary.First().Value.PictureID;
                i = firstpictureID;
            }
           
            i++;
            counter++;
            if (Math.Abs(counter) == DatabasepictureDictionary.Count || counter == 0) //>= DatabasepictureDictionary.Count + firstpictureID)
            {
                counter = 0;
                i = firstpictureID;
            }

            if (DatabasepictureDictionary.Count != 0)
            {
                //if DatabasepictureDictionary dont contains that index(picID) - repeat until find one that exists 
                while (!DatabasepictureDictionary.Keys.Contains(i))
                {
                    i++;
                }
                pictureBoxImage.Image = DatabasepictureDictionary[i].PictureImage;
                pictureBoxImage.SizeMode = PictureBoxSizeMode.Zoom;
                currentDisplayedPicture = DatabasepictureDictionary[i];
                pictureIDmaskedBox.Text = currentDisplayedPicture.PictureID.ToString();
                showCurrentAusinListbox();
                return DatabasepictureDictionary[i].AUList;
            }
            else
            {
                pictureBoxImage.Image = null;
                return null;
            }
           
        }

        protected void ShowSolutions()
        {
            foreach (Chunk chunk in solutions.Keys)
            {
                listBoxSolution.Items.Add(chunk.Label);
            }
        }

        protected void showCurrentAusinListbox()
        {
            currentAUlistbox.Items.Clear();
            listBoxSolution.Items.Clear();
            if (currentDisplayedPicture.AUList.Count != 0)
            {
                foreach (int au in currentDisplayedPicture.AUList)
                {
                    currentAUlistbox.Items.Add(au);
                }
            }


        }
        
        protected List<int> ShowPreviousImage()
        {
         
            int lastpicturesid = 0;
            if (DatabasepictureDictionary.Count == 1)
            {
                firstpictureID = currentDisplayedPicture.PictureID;
                i = firstpictureID;
                lastpicturesid = firstpictureID;
            }

            else
            {
                //Get LastPicId from DB
                ReplyMsg msg = retrievalmsg.GetLastPictureID();
                if (msg.MessageState == true)
                    lastpicturesid = (int)msg.ParamArray[0];
                 
                

            }       
           
           
            i--;
            
            if (Math.Abs(counter) == DatabasepictureDictionary.Count|| counter==0)//i < firstpictureID)
            {

                i = lastpicturesid;
            }

            counter--;
            

            if (DatabasepictureDictionary.Count != 0)
            {
                //if DatabasepictureDictionary dont contains that index(picID) - repeat until find one that exists 
                    while (!DatabasepictureDictionary.Keys.Contains(i))
                    {
                        i--;
                    }
                    pictureBoxImage.Image = DatabasepictureDictionary[i].PictureImage;

                pictureBoxImage.SizeMode = PictureBoxSizeMode.Zoom;
                currentDisplayedPicture = DatabasepictureDictionary[i];
                pictureIDmaskedBox.Text = currentDisplayedPicture.PictureID.ToString();
                showCurrentAusinListbox();
                return DatabasepictureDictionary[i].AUList;
            }
            else
            {
                pictureBoxImage.Image = null;
                return null;
            }

        }

        protected void previousImageButton_Click(object sender, EventArgs e)
        {
            RunRetrieval(ShowPreviousImage());

        }

        protected void button5_Click(object sender, EventArgs e)
        {

        }


        protected void buttonRefinementPref_Click(object sender, EventArgs e)
        {
            guiManager.refinePrefencesGui.ReEnter();
            //GuiManager.updateGui(this);
            guiManager.SwitchForms(this, guiManager.refinePrefencesGui);
        }

        protected void buttonRefinement_Click(object sender, EventArgs e)
        {
            isRefinementUsed = true;
            Messages refineMsg = new Messages();
            refineMsg.RefinementMsg(1, 1.1, 0.01, true, false, 6.25);
            Messages setIndex = new Messages();
            setIndex.SetIndexCase(true);
            labelRefinementAlert.Visible = true;

        }
        protected void labelRefinementAlert_VisibleChanged(object sender, EventArgs e)
        {
            Task t = new Task(DoStuff());
            t.Wait(1000);
            labelRefinementAlert.Visible = false ;
        }

        private Action DoStuff()
        {
            throw new NotImplementedException();
        }
   
    }
}
